/****************************************************************************************
 Copyright © 2003-2012 ZTEsoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.FeeEffectiveModeAttrHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.CalculateExpireTimeUtil;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdFeeCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <Description> <br>
 *
 * @author tengg<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2021年2月25日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler <br>
 */
@Service
@AttrHandler(FeeEffectiveModeAttrHandler.class)
public class FeeEffectiveModeAttrLinkHandler extends AbstractAttrLinkageHandler<AttrData> {

    @Autowired
    OperateInstAttrService operateInstAttrService;

    @Autowired
    IQuerySceneInstService querySceneInstService;

    /**
     * Description: <br>
     *
     * @author tengg<br>
     * @taskId <br>
     * @param attr
     * @param inst
     * @param data <br>
     */
    @Override
    public void handle(KiteAttr attr, KiteInst inst, AttrData data) {
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        List<String> serviceOfferIds = querySceneInstService.getExtParameterValue(data.getSceneInstId(),"BUSI_CHANGE_SERVICEOFFERID");

        String cateId = CuccPosServiceUtils.getCateId(data.getSceneInstId(), data.getCustId());
        //        新增逻辑五大双线资费变更，隐藏生效模式：起租时间生效
        if(null!=serviceOfferIds&&serviceOfferIds.size()==1&&LocalAttrUtils.getDoubleLineCateIds().contains(cateId)&&LocalServiceOfferConsts.SERVICE_OFFER_FEE_MODIFY.equals(serviceOfferIds.get(0))){
            attr.getAttrValues().removeIf(attrVal -> KiteStringUtils.equals(attrVal.getAttrValue(), LocalKeyConsts.EFFECTIVE_STARTING_TIME));
            if(attr.getValue().equals(LocalKeyConsts.EFFECTIVE_STARTING_TIME)){
                attr.setValue(attr.getAttrValues().get(0).getAttrValue());
            }
        }
        operateSceneInstService.setAttr(data.getSceneInstId(), inst.getInstType(), inst.getInstId(), attr);
        String value = attr.getValue();
       this.deal(inst, data, value);
       this.dealStartRentFlowNode(inst, data, value);
    }

    private void deal(KiteInst inst, AttrData data, String value) {
        //首月收取方式
        KiteAttr firstMonthkiteAttr = inst.getAttr("200000170");
        //突发带宽价格
        KiteAttr suddenlyWidthkiteAttr = inst.getAttr("210004932");
        //生效时间
        KiteAttr starteDateKiteAttr = inst.getAttr(LocalKeyConsts.STARTING_DATE_FIELD_NAME);
        //失效时间
        KiteAttr endDateKiteAttr = inst.getAttr(LocalKeyConsts.END_DATE_FIELD_NAME);

        String cateId = CuccPosServiceUtils.getCateId(data.getSceneInstId(), data.getCustId());
        //政企精品网中没有首月收取方式，但是也不属于一次性资费，走固定带宽资费逻辑，政企精品网特有资费 突发带宽价格
        //if (Objects.nonNull(firstMonthkiteAttr) || Objects.nonNull(suddenlyWidthkiteAttr)) {
        // 资费类型改为用 payType 判断
        String payType = KiteMapUtils.getString(Optional.ofNullable(ProdFeeCache.get(inst.getSpecId())).map(Offer::getOfferMap).orElse(null), "payType");
        if (!KiteStringUtils.equalsAny(payType, "one-time", "one-time-charge")) {
            if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_IMMEDIATELY)) {
                //立即生效
                //生效时间当日0点生效，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    operateInstAttrService.setAttrValue(inst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT), data.getSceneInstId(), null);
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }

                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
            }
            else if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_NEXT_MONTH)) {
              //下月生效
                //生效时间次月0点生效，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    operateInstAttrService.setAttrValue(inst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, DateFormatUtils.getFirstDayInNextMonth(DateFormatUtils.getFormatedDateTime(), DateFormatUtils.DATE_TIME_FORMAT), data.getSceneInstId(), null);
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
            }
            else if (KiteStringUtils.isEqual(value, LocalKeyConsts.CUSTOM_VALIDATION)) {
                //自定义
                //生效时间当日0点生效，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    operateInstAttrService.setAttrValue(inst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT), data.getSceneInstId(), null);
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                }
                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                }
                //趸交资费选择自定义生效,失效时间不可编辑
                if (CuccPosServiceUtils.isOneOffAddtionalOffer(inst.getSpecId()) && ActionType.A.name().equals(inst.getActionType().name())) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
            }
            else if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_STARTING_TIME)) {
                //起租时间生效
                //生效时间0000-00-00 00:00:00，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    operateInstAttrService.setAttrValue(inst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT), data.getSceneInstId(), null);
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
            }

            // 起租环节，类型为新增的资费，只能更改生效模式和生失效时间
            if(KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())) {
                String nodeCode = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "nodeCode");
                if(KiteStringUtils.isEqual(nodeCode, "OrderStartRent") && KiteStringUtils.isEqual(inst.getActionType().name(), ActionType.A.name())) {
                    inst.listAttrs().forEach(attr -> {
                        if(Objects.nonNull(attr) && !KiteStringUtils.equalsAny(attr.getFieldName(), "200000174", "200000172", "200000173")) {
                            attr.setIsEdit(KeyConsts.IFTRUE_F);
                        }
                    });
                }
            }
        }
        else {
            // 一次性费用
            //一次性费用，生效时间默认当天0点
            if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_IMMEDIATELY)) {
                //生效时间、失效时间，为当前操作日期的0点-23：59：59 ,生效时间、失效时间不可修改，置灰
                if (Objects.nonNull(starteDateKiteAttr)) {
                    operateInstAttrService.setAttrValue(inst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT), data.getSceneInstId(), null);
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
                if (Objects.nonNull(endDateKiteAttr)) {
                    // 行业5G没有首末月收取方式,生效模式默认立即生效,失效时间为2029-12-31 23:59:59
                    if (KiteStringUtils.equalsAny(cateId,"2000966")) {
                        operateInstAttrService.setAttrValue(inst, LocalKeyConsts.END_DATE_FIELD_NAME, "2029-12-31 23:59:59", data.getSceneInstId(), null);
                        endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                    } else {
                        operateInstAttrService.setAttrValue(inst, LocalKeyConsts.END_DATE_FIELD_NAME, DateFormatUtils.formatDate(KiteDateUtils.getEndOfDay(), DateFormatUtils.DATE_TIME_FORMAT), data.getSceneInstId(), null);
                        endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    }
                }
            }
            else if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_NEXT_MONTH)) {
                //下月生效
                String firstDayInNextMonth = DateFormatUtils.getFirstDayInNextMonth(DateFormatUtils.getFormatedDateTime(), DateFormatUtils.DATE_TIME_FORMAT);
                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    Date nextDate = DateFormatUtils.parseDateToFormat(firstDayInNextMonth, DateFormatUtils.DATE_TIME_FORMAT);
                    String endOfFirstDayInNextMonth = DateFormatUtils.formatDate(DateFormatUtils.getEndOfDay(nextDate), DateFormatUtils.DATE_TIME_FORMAT);
                    operateInstAttrService.setAttrValue(inst, LocalKeyConsts.END_DATE_FIELD_NAME, endOfFirstDayInNextMonth, data.getSceneInstId(), null);
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
                //生效时间次月0点生效，不可编辑
                  if (Objects.nonNull(starteDateKiteAttr)) {
                      operateInstAttrService.setAttrValue(inst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, firstDayInNextMonth, data.getSceneInstId(), null);
                      starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                  }

              }
            else if (KiteStringUtils.isEqual(value, LocalKeyConsts.CUSTOM_VALIDATION)) {
                //生效时间、失效时间，为当前操作日期的0点-23：59：59 ,生效时间、失效时间不可修改，置灰
                if (Objects.nonNull(starteDateKiteAttr)) {
                    String startDateTime = DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT);
                    // 5GRCS资费变更新增资费，生效时间默认下个月月初的第一天
                    if (InstType.ADDITIONAL_OFFER_INST.equals(inst.getInstType()) && ActionType.A.equals(inst.getActionType()) && KiteStringUtils.equals(cateId, "2000966")
                        && LocalServiceOfferConsts.SERVICE_OFFER_FEE_MODIFY.equals(data.getServiceOfferId())) {
                        startDateTime = DateFormatUtils.getMinNextMonthDate();
                    }
                    operateInstAttrService.setAttrValue(inst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, startDateTime, data.getSceneInstId(), null);
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                }
                if (Objects.nonNull(endDateKiteAttr)) {
                    operateInstAttrService.setAttrValue(inst, LocalKeyConsts.END_DATE_FIELD_NAME, "2029-12-31 23:59:59", data.getSceneInstId(), null);
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                }
            }
        }
        //计算失效时间
        CalculateExpireTimeUtil.dealExpireTime(suddenlyWidthkiteAttr,inst,data);
    }

    private void dealStartRentFlowNode(KiteInst inst, AttrData data, String value) {
        String sceneInstId = data.getSceneInstId();
        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode", "");
        if (!"OrderStartRent".equals(nodeCode) || !ActionType.A.name().equals(inst.getActionType().name())) {
            return;
        }
        //如果是起租时间生效,刷新资费的生效时间
        if (LocalKeyConsts.EFFECTIVE_STARTING_TIME.equals(value)) {
            //起租时间
            KiteAttr startRentTimeAttr = querySceneInstService.getCommonAttr(sceneInstId, "REC_10057");
            operateInstAttrService.setAttrValue(inst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, startRentTimeAttr.getValue(), data.getSceneInstId(), null);
        }
    }

    /**
     * Description: <br>
     *
     * @author tengg<br>
     * @taskId <br>
     * @param attr
     * @param inst
     * @param data <br>
     */
    @Override
    public void handleStyle(KiteAttr attr, KiteInst inst, AttrData data) {
        // TODO Auto-generated method stub

    }

}
